package cn.micro.keep.accounts.service.impl;

import cn.micro.keep.accounts.entity.AccountOdsRecord;
import cn.micro.keep.accounts.entity.AccountOdsRecordImg;
import cn.micro.keep.accounts.entity.FileInfo;
import cn.micro.keep.accounts.mapper.AccountOdsRecordImgMapper;
import cn.micro.keep.accounts.mybatis.BasicServiceImpl;
import cn.micro.keep.accounts.service.AccountOdsRecordImgService;
import cn.micro.keep.accounts.service.OssService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 账单图片信息表 服务实现类
 * </p>
 *
 * @author 柘阳科技
 * @since 2023-11-08
 */
@Service
@RequiredArgsConstructor
public class AccountOdsRecordImgServiceImpl extends BasicServiceImpl<AccountOdsRecordImgMapper, AccountOdsRecordImg> implements AccountOdsRecordImgService {

    @Value("${file.account-record-path}")
    private String recordPath;

    private final OssService ossService;

    @Value("${oss.local.base-path}")
    private String basePath;

    @Override
    public boolean uploadRecordImg(MultipartFile[] files) {
        List<AccountOdsRecordImg> recordImgList = new ArrayList<>();
        for (MultipartFile file : files){
            FileInfo fileInfo = ossService.uploadFileByUrl(file, recordPath);
            if (fileInfo != null){
                AccountOdsRecordImg recordImg = new AccountOdsRecordImg();
                recordImg.setImgUrl(fileInfo.getUrl());
                recordImg.setImgName(fileInfo.getName());
                recordImgList.add(recordImg);
            }
        }
        if (!recordImgList.isEmpty()){
            this.baseMapper.insertBatch(recordImgList);
            return true;
        }
        return false;
    }

    @Override
    public boolean removeRecordImg(Long imgId) {
        AccountOdsRecordImg recordImg = this.getById(imgId);
        if (recordImg == null || recordImg.getImgUrl() == null){
            throw new RuntimeException("图片不存在");
        }
        if (ossService.deleteFile(recordImg.getImgUrl())){
           this.baseMapper.deleteById(imgId);
        }
        return false;
    }

    @Override
    public void viewRecordImg(Long imgId, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        AccountOdsRecordImg recordImg = this.getById(imgId);
        if (recordImg == null || recordImg.getImgUrl() == null){
            throw new RuntimeException("图片不存在");
        }
        File file = Paths.get(basePath, recordImg.getImgUrl()).toFile();
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(recordImg.getImgName().getBytes("utf-8"),"ISO8859-1"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("success");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
